package com.shensi.adminCollect.service.station.impl;

import com.shensi.common.core.domain.entity.SysUser;
import com.shensi.common.core.exception.BaseException;
import com.shensi.common.core.utils.SecurityUtils;
import com.shensi.common.core.utils.StringUtils;
import com.shensi.adminCollect.domain.station.*;
import com.shensi.adminCollect.domain.station.vo.CommodityExportErrorVo;
import com.shensi.adminCollect.mapper.station.WarehouseDetailsMapper;
import com.shensi.adminCollect.service.station.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service("warehouseService")
@Slf4j
public class WarehouseDetailsServiceImpl implements WarehouseDetailsService {

    @Autowired
    private WarehouseDetailsMapper warehouseMapper;

    @Autowired
    private WarehouseBatchService warehouseBatchService;

    @Autowired
    private IStationService stationService;

    @Autowired
    private IEnterpriseService enterpriseService;

    @Autowired
    private CommodityService commodityService;

    @Autowired
    private INonOilCategoryService nonOilCategoryService;

    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public void addWarehouse(WarehouseDetails warehouse) {
        Station station = stationService.selectStationById(warehouse.getStationId());
        Enterprise enterprise = enterpriseService.selectEnterpriseById(station.getEnterpriseId());
        SysUser user = SecurityUtils.getLoginUser().getUser();
        WarehouseBatch warehouseBatch = new WarehouseBatch();
        warehouseBatch.setStationId(station.getStationId());
        warehouseBatch.setStationName(station.getStationName());
        warehouseBatch.setEnterpriseId(enterprise.getEnterpriseId());
        warehouseBatch.setEnterpriseName(enterprise.getEnterpriseName());
        warehouseBatch.setCommodityNum(warehouse.getCommodityNum());
        warehouseBatch.setCommodityPrice(warehouse.getCommodityPrice());
        warehouseBatch.setCreateUser(user.getUserName());
        WarehouseBatch batch = warehouseBatchService.addWarehouseBatch(warehouseBatch);
        List<WarehouseDetails> warehouseList = warehouse.getWarehouseList();
        for (WarehouseDetails newWarehouse : warehouseList) {
            newWarehouse.setStationId(station.getStationId());
            newWarehouse.setStationName(station.getStationName());
            newWarehouse.setEnterpriseId(enterprise.getEnterpriseId());
            newWarehouse.setEnterpriseName(enterprise.getEnterpriseName());
            newWarehouse.setBatchId(batch.getId());
            warehouseMapper.insertSelective(newWarehouse);

            // 更新库存
            if(Objects.isNull(newWarehouse.getCommodityId())){
                throw new BaseException("没有指定商品");
            }
            Commodity oldCommodity = commodityService.queryById(newWarehouse.getCommodityId());
            if(Objects.isNull(oldCommodity)){
                throw new BaseException(newWarehouse.getCategoryName() + "商品不存在");
            }
            Commodity commodity = new Commodity();
            commodity.setCommodityId(newWarehouse.getCommodityId());
            commodity.setInventory(oldCommodity.getInventory() + newWarehouse.getCommodityNum());
            commodityService.update(commodity);
        }


    }

    @Override
    public List<WarehouseDetails> selectWarehouseList(Long batchId) {
        List<WarehouseDetails> warehouseList = warehouseMapper.selectWarehouseByBatchId(batchId);
        for (WarehouseDetails warehouse : warehouseList) {
            NonOilCategory category = nonOilCategoryService.queryById(warehouse.getCategoryId());
            warehouse.setCategoryName(category.getCategoryName());
        }
        return warehouseList;
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public void addWarehouseList(List<Commodity> commodityList) {
        Long stationId = commodityList.get(0).getStationId();
        Station station = stationService.selectStationById(stationId);
        Enterprise enterprise = enterpriseService.selectEnterpriseById(station.getEnterpriseId());
        SysUser user = SecurityUtils.getLoginUser().getUser();
        WarehouseBatch warehouseBatch = new WarehouseBatch();
        warehouseBatch.setStationId(station.getStationId());
        warehouseBatch.setStationName(station.getStationName());
        warehouseBatch.setEnterpriseId(enterprise.getEnterpriseId());
        warehouseBatch.setEnterpriseName(enterprise.getEnterpriseName());
        warehouseBatch.setCreateUser(user.getUserName());
        WarehouseBatch batch = warehouseBatchService.addWarehouseBatch(warehouseBatch);
        Long commodityNum = 0l;
        BigDecimal commodityPrice = BigDecimal.ZERO;
        for (Commodity commodity : commodityList) {
            WarehouseDetails newWarehouse = new WarehouseDetails();
            newWarehouse.setStationId(station.getStationId());
            newWarehouse.setStationName(station.getStationName());
            newWarehouse.setEnterpriseId(enterprise.getEnterpriseId());
            newWarehouse.setEnterpriseName(enterprise.getEnterpriseName());
            newWarehouse.setBatchId(batch.getId());
            newWarehouse.setCommodityId(commodity.getCommodityId());
            newWarehouse.setCommodityName(commodity.getCommodityName());
            newWarehouse.setCommodityCode(commodity.getCommodityCode());
            newWarehouse.setCategoryId(commodity.getCategoryId());
            newWarehouse.setCategoryName(commodity.getCategoryName());
            newWarehouse.setUnit(commodity.getUnit());
            newWarehouse.setInventoryQuantity(commodity.getInventoryQuantity());
            newWarehouse.setSalePrice(commodity.getSalePrice());
            newWarehouse.setTotalPrice(commodity.getTotalPrice());
            warehouseMapper.insertSelective(newWarehouse);

            // 更新库存
            if(Objects.isNull(newWarehouse.getCommodityId())){
                throw new BaseException("没有指定商品");
            }
            Commodity oldCommodity = commodityService.queryById(newWarehouse.getCommodityId());
            if(Objects.isNull(oldCommodity)){
                throw new BaseException(newWarehouse.getCategoryName() + "商品不存在");
            }
            Commodity newCommodity = new Commodity();
            newCommodity.setCommodityId(newWarehouse.getCommodityId());
            if(Objects.isNull(oldCommodity.getInventory())){
                newCommodity.setInventory(commodity.getInventoryQuantity());
            } else {
                newCommodity.setInventory(oldCommodity.getInventory() + commodity.getInventoryQuantity());
            }
            newCommodity.setUpdateTime(new Date());
            commodityService.update(newCommodity);
            commodityNum = commodityNum + commodity.getInventoryQuantity();
            commodityPrice = commodityPrice.add(Objects.nonNull(commodity.getTotalPrice()) ? commodity.getTotalPrice() : BigDecimal.ZERO);
        }
        WarehouseBatch newBatch = new WarehouseBatch();
        newBatch.setId(batch.getId());
        newBatch.setCommodityNum(commodityNum);
        newBatch.setCommodityPrice(commodityPrice);
        warehouseBatchService.updateWarehouseBatch(newBatch);
    }

    @Override
    public List<CommodityExportErrorVo> exportAddWarehouseList(List<Commodity> commodityList) {
        // 校验入库数据
        return checkCommodityExports(commodityList);
    }

    private List<CommodityExportErrorVo> checkCommodityExports(List<Commodity> commodityList){
        List<CommodityExportErrorVo> commodityExportErrorVoList = new ArrayList<>();
        int num = 1;
        Long stationId = 0L;
        List<Commodity> commodities = new ArrayList<>();
        for (Commodity commodity : commodityList) {
            if(Objects.isNull(commodity)){
                CommodityExportErrorVo commodityExportErrorVo = new CommodityExportErrorVo();
                commodityExportErrorVo.setNum(num);
                commodityExportErrorVo.setReason("整行数据不存在");
                commodityExportErrorVoList.add(commodityExportErrorVo);
                num++;
                continue;
            }
            String reason = "";
            if(Objects.nonNull(commodity.getStationId()) && (stationId == 0L)){
                stationId = commodity.getStationId();
            }
            if(Objects.isNull(commodity.getStationId())){
                reason = reason + "油站id不为空,";
            }
            if(StringUtils.isEmpty(commodity.getBarCode())){
                reason = reason + "商品条码不为空,";
            }

            if(Objects.isNull(commodity.getInventoryQuantity()) || commodity.getInventoryQuantity() <= 0){
                reason = reason + "入库数量不正确,";
            }

            if(Objects.nonNull(commodity.getStationId()) && stationId != 0L && !stationId.equals(commodity.getStationId())){
                reason = reason + "入库油站id不一致,";
            }

            if(StringUtils.isEmpty(commodity.getCommodityName())){
                reason = reason + "商品名称不为空";
            }
            if(StringUtils.isEmpty(commodity.getStationName())){
                reason = reason + "油站名称不为空";
            }
            Station station = new Station();
            Commodity query = new Commodity();
            if(Objects.nonNull(commodity.getStationId())){
                station = stationService.selectStationById(commodity.getStationId());
                if(Objects.isNull(station)){
                    reason = reason + "入库油站不存在,";
                } else if(!commodity.getStationName().equals(station.getStationName())){
                    reason = reason + "入库油站名称错误,";
                }else if(StringUtils.isNotEmpty(commodity.getBarCode())){
                    Commodity com = new Commodity();
                    com.setStationId(commodity.getStationId());
                    com.setBarCode(commodity.getBarCode());
                    query = commodityService.queryCommodity(com);
                    if(Objects.isNull(query)){
                        reason = reason + "商品条码不存在,";
                    } else if(!commodity.getCommodityName().equals(query.getCommodityName())){
                        reason = reason + "商品名称错误,";
                    }
                }
            }

            if(reason.length() >0){
                CommodityExportErrorVo commodityExportErrorVo = new CommodityExportErrorVo();
                commodityExportErrorVo.setNum(num);
                commodityExportErrorVo.setReason(reason);
                commodityExportErrorVo.setBarCode(commodity.getBarCode());
                commodityExportErrorVo.setCommodityName(commodity.getCommodityName());
                commodityExportErrorVo.setInventoryQuantity(commodity.getInventoryQuantity());
                commodityExportErrorVoList.add(commodityExportErrorVo);
            } else {
                query.setInventoryQuantity(commodity.getInventoryQuantity());
                query.setTotalPrice(query.getSalePrice().multiply(BigDecimal.valueOf(commodity.getInventoryQuantity())));
                NonOilCategory nonOilCategory = nonOilCategoryService.queryById(query.getCategoryId());
                query.setCategoryName(nonOilCategory.getCategoryName());
                commodities.add(query);
            }
            num++;
        }
        if(CollectionUtils.isNotEmpty(commodities)){
            // 入库
            addWarehouseList(commodities);
        }
        return commodityExportErrorVoList;
    }
}
